<template>
  <el-upload ref="uploadAttaches" action="https://up-z2.qiniup.com" :data="{}"
             :file-list="attaches" multiple
             :before-upload="beforeUpload"
             :on-change="handleChange"
             :on-error="handleError"
             :on-remove="handleRemove"
             :before-remove="beforeRemove">
    <el-button slot="trigger" size="small">选择文件</el-button>
    <div slot="tip" class="el-upload__tip info body-line-height">单个附件大小不得超过600MB。</div>
  </el-upload>
</template>

<script>
export default {
  name: 'UploadAttaches', // 上传附件
  props: {
    attaches: {
      type: Array,
      required: true,
    },
    limitSize: { // 上传限制 { size: 629145600, msg: '错误信息' } 单位是 字节(b)
      type: Object,
      default: () => ({ size: 629145600, msg: '单个附件大小超过600MB' }),
    },
  },
  methods: {
    // 获取上传密钥
    getUploadToken() {
      return new Promise((resolve, reject) => {
        this.$api.other.uploadToken()
          .then(res => resolve(res.data.token))
          .catch((err) => {
            this.$message.error('获取上传密钥失败', err);
            reject(err);
          });
      });
    },
    // 上传前添加必要的上传密钥等信息
    async beforeUpload(file) {
      if (this.limitSize && file.size > this.limitSize.size) { // 限制大小
        this.$message.error(this.limitSize.msg);
        return false;
      }
      const uploadToken = await this.getUploadToken();
      return Object.assign(this.$refs.uploadAttaches.data, {
        token: uploadToken,
        key: `attaches-${new Date().getTime()}/${file.name}`,
        'x:user_id': this.$store.state.currentUser.id,
      });
    },
    // 文件列表变化
    handleChange(file, fileList) { this.$emit('update:attaches', fileList); },
    // 上传失败
    handleError(err) { this.$message.error(`上传失败 ${err}`); },
    // 移出列表
    handleRemove(file, fileList) { this.$emit('update:attaches', fileList); },
    // 移出前的确认
    beforeRemove(file) {
      const msg = file.status === 'success' ? `是否移除 ${file.name}` : `是否取消上传 ${file.name}`;
      return this.$confirm(msg, '提示', {
        customClass: 'confirm-left',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      });
    },
  },
};
</script>

<style></style>
